package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.service.CartService;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

public class RemoveItemFromCartServlet extends HttpServlet {

    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
    private static final String ERROR = "/WEB-INF/jsp/common/Error.jsp";

    private String workingItemId;
    private Cart cart;
    private CartService cartService;
    private String pre = "0";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        cartService = new CartService();
        workingItemId = request.getParameter("workingItemId");
        if (!workingItemId.equals(pre)) {
            HttpSession session = request.getSession();
            cart = (Cart) session.getAttribute("cart");

            Item item = cart.removeItemById(workingItemId);
            cart = (Cart) session.getAttribute("cart");


            if (item == null) {
                session.setAttribute("message", "Attempted to remove null CartItem from Cart.");
                request.getRequestDispatcher(ERROR).forward(request, response);
            } else {
                if(session.getAttribute("account")!=null)
                {
                    Account account = (Account)session.getAttribute("account");
                    cartService.removeItemByUserIdAndItemId(account.getUsername(),workingItemId);

                }
                request.getRequestDispatcher(VIEW_CART).forward(request,response);
            }
            pre = workingItemId;
        }
        else
        {
            request.getRequestDispatcher(VIEW_CART).forward(request,response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
